#include"../include/cmd.h"

int cp_command(int fd,cmd_t* cmd)
{
    char* srcpathname=cmd->args[0].arg;
    char* dstpathname=cmd->args[1].arg;

    //判断文件还是目录                                                            
    struct stat st;
    memset(&st,0,sizeof(st));
    stat(srcpathname,&st);
    //文件复制
    int recvidx;    //返回值
    if((st.st_mode&S_IFMT)==S_IFREG)
    {
        //复制文件
        recvidx=copy_file(srcpathname,dstpathname);
        send(fd,&recvidx,4,MSG_WAITALL);
        return recvidx;
    }   

    //递归复制目录
    recvidx=copy_dir(srcpathname,dstpathname);  //recvidx
    send(fd,&recvidx,4,MSG_WAITALL);        //0成功
    return recvidx;                             //-1失败

}
int copy_file(char* srcpathname,char* dstpathname)
{
    int srcfd=open(srcpathname,O_RDONLY);
    if(srcfd==-1)
    {
        return -1;
    }
    int dstfd=open(dstpathname,O_RDWR|O_CREAT|O_TRUNC,0664);
    if(dstfd==-1)
    {
        return -1;
    }
    char buf[1024]={0};
    int len;

    while((len=read(srcfd,buf,sizeof(buf)))!=0)
    {
        if(len==-1)
        {
            return -1;
        }
        write(dstfd,buf,len);
    }
    return 0;
}

int copy_dir(char* srcpathname,char* dstpathname)
{
    DIR* pdir=opendir(srcpathname);    
    if(pdir==NULL)
    {
        return -1;
    }
    int ret=mkdir(dstpathname,0775);
    if(ret==-1)
    {
        return -1;
    }
    struct dirent* pdirent;

    while((pdirent=readdir(pdir))!=NULL)
    {
        //忽略.   .. 文件
        char* name=pdirent->d_name;
        if((!strcmp(name,"."))||(!strcmp(name,"..")))
        {
            continue;
        }
        char srcfilename[1024]={0};
        char dstfilename[1024]={0};

        sprintf(srcfilename,"%s/%s",srcpathname,name);
        sprintf(dstfilename,"%s/%s",dstpathname,name);

        if(pdirent->d_type==DT_DIR)
        {
            //递归复制目录
            ret=copy_dir(srcfilename,dstfilename);      
            if(ret==-1)
            {
                return -1;
            }
        }
        else
        {
            //复制文件
            ret=copy_file(srcfilename,dstfilename);
            if(ret==-1)
            {
                return -1;
            }
        }
    }
    return 0;
}

